<template>
  <Modal v-model="drawer.show" :closable="drawer.status == 'read'" :width="90" :mask-closable="false" :styles="styles">
    <span slot="header">{{ lang.title }}<span style="font-weight: 600;">{{this.title}}</span></span>
    <div slot="footer">
      <Button v-if="drawer.status!=='read'" @click="drawer.show = false">{{ $t(`global.cancel`) }}</Button>
      <Button
        type="primary"
        class="ivu-ml"
        @click="ok"
        >{{ drawer.status!=='read' ? $t(`global.save`) : $t(`global.close`) }}</Button
      >
    </div>
    <div v-if="drawer.show && classObject.record" class="eventManage">
      <Row :gutter="8" :wrap="false" class="contentwp">
        <Col flex="200px" style="">
          <Menu
            style="width:100%;height:100%;"
            :active-name="currentMenu"
            @on-select="selectMenu"
            :open-names="['service']"
          >
            <MenuItem name="start">{{ lang.start }}</MenuItem>
            <Submenu name="service">
              <template slot="title"> <Icon type="ios-list" /> {{ lang.service }} </template>
              <MenuItem
                v-for="(item, index) in data.service"
                :key="index"
                :name="'step' + index"
              >
                {{`${lang.step}:${index+1}`}}
                <Icon style="float: right;color:red" type="md-remove" @click.native="removeStep(index)"> </Icon>
              </MenuItem>
              <MenuItem name="new" @click.native="newAddStep">{{ lang.newStep }}</MenuItem>
            </Submenu>
            <MenuItem name="back">{{ lang.back }}</MenuItem>
          </Menu>
        </Col>
        <Col flex="auto" style="padding:10px;">
          <Form :labelWidth="100">
            <div v-if="currentMenu === 'start'" class="startwp">
              <Card :title="lang.globalState">
                <cfgEditTable :value="data.globalState" :columns="globalStateColumns" :showNum="false" />
              </Card>
              <Card :title="lang.params">
                <cfgEditTable :value="data.params" :columns="paramsColumns" :showNum="false" />
              </Card>
              <Card :title="lang.globalScalar">
                <cfgEditTable :value="data.globalScalar" :columns="globalScalarColumns" :showNum="false" />
              </Card>
              <!-- <FieldItem
                v-model="data.condition"
                :config="{type: 'text', clearable: true}"
                :formItemProps="{label: lang.condition, labelWidth: 60}"
              /> -->
            </div>
            <div v-else-if="currentMenu==='back'" class="backwp">
              <FieldItem v-model="data.back.isBack" :config="{type: 'switch'}" :formItemProps="{label: lang.isBack}" />
              <Card :title="lang.state">
                <cfgEditTable :value="data.back.state" :columns="backStateColumns" :showNum="false" />
              </Card>
            </div>
            <div v-else-if="currentMenu.includes('step') && curService" class="servicewp">
              <!-- <FieldItem
                v-model="curService.model"
                @change="modelChange"
                :config="{type: 'cascader', options: modelTree, clearable: true}"
                :formItemProps="{label: lang.model, labelWidth: 60}"
              /> -->
              <FieldItem
                v-model="curService.model"
                @change="modelChange"
                :config="{type: 'select', options: modelOptions, clearable: true}"
                :formItemProps="{label: lang.model, labelWidth: 60}"
              />
              <FieldItem
                v-model="curService.action"
                @change="actionChange"
                :config="{type: 'select', options: actionOptions, clearable: true}"
                :formItemProps="{label: lang.action, labelWidth: 60}"
              />
              <Card :title="lang.state">
                <cfgEditTable :value="curService.state" :columns="stateColumns" :showNum="false" :addTpl="{pointer: {}}" />
              </Card>
              <Card :title="lang.scalar">
                <cfgEditTable :value="curService.scalar" :columns="scalarColumns" :showNum="false" />
              </Card>
              <Card :title="lang.refs">
                <cfgEditTable :value="curService.refs" :columns="refsColumns" :showNum="false"/>
              </Card>
              <Card :title="lang.resultState">
                <FieldItem
                  v-model="curService.result.isResult"
                  :config="{type: 'switch'}"
                  :formItemProps="{label: lang.isResult}"
                />
                <cfgEditTable :value="curService.result.state" :columns="resultStateColumns" :showNum="false" />
              </Card>
            </div>
          </Form>
        </Col>
      </Row>
    </div>
    <!-- <Button @click="test">test</Button> -->
  </Modal>
</template>

<script>
import { mapState } from "vuex";
import config from './config'

export default {
  name: "eventModal",
  data() {
    return {
      styles: {top: '50px', maxWidth: '1200px'},
      menuRate: 6,
      currentMenu: 'start',
      model: this.$modelObject.create('event'),
      modelOptions: config.modelOptions,
      // modelOptions: ['Business', 'Consume'].map(item => ({label: item, value: item})),
      // actionOptions: ['createEntityToContainer','add','delete', 'query'].map(item => ({label: item, value: item})),
      // actionMap: {
      //   createEntityToContainer: ['type', 'className', 'name', 'values'],
      //   add: ['type', 'className', 'name', 'values'],
      //   delete: ['ids'],
      //   query: ['condition'],
      // },
    }
  },
  
  beforeMount() {
    // this.selectMenu('step0')
  },
  methods: {
    ok() {
      this.classObject.record.event = this.data
      // console.log("file: eventModal.vue:63  ok", this.data)
      this.selectMenu('start')
      this.$emit('submit')
    },
    selectMenu(name) {
      this.currentMenu = name
    },
    removeStep(pos) {
      this.data.service.splice(pos, 1);
      this.currentMenu = 'start'
    },
    newAddStep() {
      this.data.service.push(this.model.serviceItemTpl());
      this.$nextTick(() => {
        this.currentMenu = 'step' + (this.data.service.length - 1)
      })
    },
    updateRefs() {
      // 根据选择的model和action，动态展示name
      if (this.curService && this.curService.action ) {
        this.curService.refs = config.refsMap[`${this.curService.model}_${this.curService.action}`] || []
      } else {
        this.curService.refs = []
      }
    },
    modelChange() {
      this.curService.action = ''
      this.curService.refs = []
    },
    actionChange() {
      this.updateRefs()
    },
    test() {
      console.log("file: eventModal.vue:161  test", this.data, this.currentMenu)
    },
    getOptions(arr,labelName,valueName, prefix=''){
      let res = []
      try {
      let tmp = JSON.parse(JSON.stringify(arr))
      tmp.forEach(item=>{
          let label = !!labelName ? item[labelName] : item
          let value = !!valueName ? item[valueName] : item
          label && res.push({
              label: prefix + label,
              value: prefix + value,
          })
      })
      } catch(e) {
        console.log("file: eventModal.vue:182  getOptions  e:", e)
      }
      return res
    },
    updateLocale() {
    }
  },
  watch: {
    G_Locale: {
      handler(val) {
        this.updateLocale()
      },
      immediate: true
    },
    'drawer.show'(val) {
      if (val) {
      }
    },
  },
  computed: {
    ...mapState('admin/model',[
        'modelTree',
    ]),
    data() {
      return this.classObject.record.event
    },
    curService() {
      let stepIndex= this.currentMenu.includes('step') ? this.currentMenu.replace('step', '') * 1 : -1
      let res = this.currentMenu.includes('step') && stepIndex >= 0 ? this.data.service[stepIndex] : null
      return res
    },
    actionOptions() {
      if (!this.currentMenu.includes('step') || !this.curService.model) { return [] }
      return config.actionMap[this.curService.model]
    },
    //#region columns
    globalStateColumns() {
      return [
          {
            key: 'type',
            title: this.lang.paramType,
            elementName: 'fieldCell',
            props: {
              // record：map格式，单条记录；records：listMap格式，多条记录；map：map格式，kv组合；object：单值
              config: { type: 'select', clearable: true, options: ['record', 'records', 'map', 'object'].map(item => {
                return {label: item, value: item}
              }) }
            }
          },
          {
            key: 'name',
            title: this.lang.paramName,
            elementName: 'fieldCell',
            props: { config: { type: 'text', clearable: true } }
          },
          { slot: 'operation', }
        ]
    },
    paramsColumns() {
      return [
        {
          key: 'name',
          title: this.lang.paramName,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        { slot: 'operation', }
      ]
    },
    globalScalarColumns() {
      return [
        {
          key: 'name',
          title: this.lang.paramName,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        {
          key: 'value',
          title: this.lang.paramValue,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        { slot: 'operation', }
      ]
    },
    scalarColumns() {
      if (!this.currentMenu.includes('step')) { return [] }
      return [
        {
          key: 'name',
          title: this.lang.paramName,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        {
          key: 'value',
          title: this.lang.paramValue,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        { slot: 'operation', }
      ]
    },
    stateColumns() {
      if (!this.currentMenu.includes('step')) { return [] }
      return [
        {
          key: 'name',
          title: this.lang.paramName,
          width: 120,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        {
          key: 'value',
          title: this.lang.paramValue,
          width: 120,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        {
          key: 'pointer',
          title: this.lang.pointer,
          width: 300,
          elementName: 'cfgCascaderModel',
          props: { config: { type: 'text', clearable: true } }
        },
        {
          key: 'pointer.condition',
          title: this.lang.condition,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        { slot: 'operation', }
      ]
    },
    refsColumns() {
      if (!this.currentMenu.includes('step')) { return [] }
      let refsOptions = []

      refsOptions = refsOptions.concat(this.getOptions(this.data.globalState, 'name', 'name', 'globalState.'))
        .concat(this.getOptions(this.data.params, 'name', 'name', 'params.'))
        .concat(this.getOptions(this.data.globalScalar, 'name', 'name', 'globalScalar.'));

      if (this.curService) {
        refsOptions = refsOptions.concat(this.getOptions(this.curService.scalar, 'name', 'name', 'scalar.'))
          .concat(this.getOptions(this.curService.state, 'name', 'name', 'state.'));
      }
      console.log("file: eventModal.vue:327  refsColumns  refsOptions:", this.currentMenu,this.curService, refsOptions)
      return [
        {
          key: 'name',
          title: this.lang.paramName,
          elementName: 'fieldCell',
          props: { config: { type: 'text', disabled: true } }
        },
        {
          key: 'value',
          title: this.lang.paramValue,
          elementName: 'fieldCell',
          props: { config: { type: 'select', clearable: true, options: refsOptions } }
        },
        // { slot: 'operation', }
      ]
    },
    resultStateColumns() {
      if (!this.currentMenu.includes('step')) { return [] }
      let globalStateOptions = []
      this.data.globalState.forEach(item => {
        item.name && globalStateOptions.push({label: item.name, value: item.name})
      })

      return [
        {
          key: 'name',
          title: this.lang.paramName,
          elementName: 'fieldCell',
          props: { config: { type: 'select', clearable: true, options: globalStateOptions }}
        },
        {
          key: 'path',
          title: this.lang.paramPath,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        { slot: 'operation', }
      ]
    },
    backStateColumns() {
      if (this.currentMenu !== 'back') { return [] }
      let globalStateOptions = []
      this.data.globalState.forEach(item => {
        item.name && globalStateOptions.push({label: item.name, value: item.name})
      })

      return [
        {
          key: 'name',
          title: this.lang.paramName,
          elementName: 'fieldCell',
          props: { config: { type: 'select', clearable: true, options: globalStateOptions }}
        },
        {
          key: 'value',
          title: this.lang.paramValue,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } }
        },
        { slot: 'operation', }
      ]
      //#endregion
    },
    lang() {
      return {
        "zh-CN": {
          title: '事件编辑',
          start: '事件开始',
          service: '事件步骤',
          step: '步骤',
          newStep: '新增步骤',
          back: '事件返回',
          // param
          model: '模型',
          action: '方法',
          globalState: '全局变量表',
          params: '全局参数表',
          globalScalar: '全局标量表',
          paramType: '类型',
          paramName: '名称',
          paramValue: '数值',
          paramPath: '路径',
          pointer: '指针',
          condition: '条件',
          // service
          state: '变量表',
          scalar: '标量表',
          refs: '引用表',
          resultState: '返回',
          isResult: '保存返回值',
          isBack: '返回结果',
        },
        "en-US": {
          title: 'event edit',
          start: 'event start',
          service: 'event step',
          step: 'step',
          newStep: 'new step',
          back: 'event back',
          // param
          model: 'model',
          action: 'action',
          globalState: 'global state',
          params: 'global params',
          globalScalar: 'global scalar',
          paramType: 'type',
          paramName: 'name',
          paramValue: 'value',
          paramPath: 'path',
          pointer: 'pointer',
          condition: 'condition',
          // service
          state: 'state',
          scalar: 'scalar',
          refs: 'ref',
          resultState: 'result state',
          isResult: 'save result value',
          isBack: 'back result',
        },
      }[this.G_Locale];
    },
  },
  props: {
    drawer: {
      default: () => {
        return {
          status: 'edit', // new edit read
          show: true,
        };
      }
    },
    title: {
      default: ''
    },
    classObject: {
      default() {
        return null
      }
    },
  },
}
</script>

<style lang="less">
.eventManage {
  .contentwp {
    > .ivu-col {
      max-height: calc(~"100vh - 230px");
      overflow: auto;
    }
  }
  .c-formItem {
    margin-bottom: 4px;
  }
  .ivu-card {
    margin-bottom: 12px;
    &:hover {
      box-shadow: none;
    }
  }
  .ivu-table {
    // padding: 0 8px;
    td {
      height: 36px;
    }
  }
}
</style>
